//
//  CollectionTableViewCell.m
//  Shengzhuli
//
//  Created by FXGuo on 2017/5/11.
//  Copyright © 2017年 kamangkeji. All rights reserved.
//

#import "CollectionTableViewCell.h"
#import "ItemCollectionViewCell.h"
#import "HorizontalPageFlowlayout.h"

@interface CollectionTableViewCell()<UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic,weak) UICollectionView *collection;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;

@end

@implementation CollectionTableViewCell

- (void)awakeFromNib
{
    [super awakeFromNib];
    
    HorizontalPageFlowlayout *flow = [[HorizontalPageFlowlayout alloc] initWithRowCount:2 itemCountPerRow:4];
    [flow setColumnSpacing:0 rowSpacing:0 edgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    
    CGFloat width = ScreenW/4.0;
    flow.itemSize = CGSizeMake(width, width);
    flow.minimumInteritemSpacing = 0;
    flow.minimumLineSpacing = 0;
    flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    UICollectionView *collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, ScreenW/4*2) collectionViewLayout:flow];
    collection.backgroundColor = [UIColor whiteColor];
    collection.delegate = self;
    collection.dataSource = self;
    collection.pagingEnabled = YES;
    collection.showsHorizontalScrollIndicator = NO;
    [collection registerNib:[UINib nibWithNibName:NSStringFromClass([ItemCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([ItemCollectionViewCell class])];
    self.collection = collection;
    [self.contentView addSubview:collection];
}
- (void)setTypes:(NSArray *)types
{
    _types = types;
    self.pageControl.numberOfPages = (NSInteger)(self.types.count+8-1)/8;
    [self.collection reloadData];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.types.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([ItemCollectionViewCell class]) forIndexPath:indexPath];
//    NSInteger count;
//    NSInteger page = indexPath.item/8;
//    //通过排列数据实现横向排列
//    if (indexPath.item%2 == 0) {
//        count = indexPath.item/2+4*page;
//    }else {
//        count = indexPath.row+(4-((indexPath.row%8)+1)/2);
//    }
    cell.model = self.types[indexPath.item];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.typeClickBlock) {
        BOOL isLast = (indexPath.item == self.types.count-1);
        self.typeClickBlock(self.types[indexPath.item],isLast);
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    int page = scrollView.contentOffset.x/ScreenW + 0.5;
    self.pageControl.currentPage = page;
}

@end
